//
//  FabuViewController.m
//  Xiangmu
//
//  Created by 이경인 on 2017/10/22.
//  Copyright © 2017年 LIJINGREN. All rights reserved.
//

#import "FabuViewController.h"
#import <AFNetworking.h>
@interface FabuViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    UIImage *image;
    NSString *fullPath;
}

@end

@implementation FabuViewController

- (void)viewDidLoad {
    
    UIBarButtonItem *fabu = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"fabu.jpg" ] style:UIBarButtonItemStyleDone target:self action:@selector(fabu)];
    self.navigationItem.rightBarButtonItem = fabu;
    
    self.imageView.userInteractionEnabled = YES;
    self.fabuTextView.layer.borderWidth = 1;
    self.fabuTextView.layer.borderColor = [[UIColor lightGrayColor]CGColor];
    self.fabuTextView.layer.masksToBounds =YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [self.imageView addGestureRecognizer:singleTap];
}
-(void)fabu{
    NSDictionary *dict1 = @{@"image":fullPath};
    NSUserDefaults *userDe = [NSUserDefaults standardUserDefaults];
  NSString *str =  [userDe objectForKey:@"userID"];
    NSDictionary *dict =@{@"userid":str,@"title":self.fabuTextView.text};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSString *urlstr = [NSString stringWithFormat:@"http://172.24.10.175/workout/api.php/fcreate?userid=%@,title=%@",str,self.fabuTextView.text];
    [manager POST:urlstr parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
     NSString *imagePath = [NSString stringWithFormat:@"%@",dict1[@"image"]];
     UIImage *image1 = self.imageView.image;
     NSData *data = [self resetSizeOfImageData:image1 maxSize:0.1];
     NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
     formatter.dateFormat = @"yyyyMMDDHHmmss";
     NSString *str = [formatter stringFromDate:[NSDate date]];
     NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
     [formData appendPartWithFileData:data name:@"thumb" fileName:fileName mimeType:@"image/png"];
     
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
    
}
-(NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize
{
    //先调整分辨率
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
    
    CGFloat tempHeight = newSize.height / 1024;
    CGFloat tempWidth = newSize.width / 1024;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //调整大小
    NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
    NSUInteger sizeOrigin = [imageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    if (sizeOriginKB > maxSize) {
        NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.01);
        return finallImageData;
    }
    
    return imageData;
}
- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer {
         [self imageChanage];
}
 


- (IBAction)image:(id)sender {

}
-(void)imageChanage{
    UIActionSheet *sheet;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        sheet = [[UIActionSheet alloc]initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    }else{
        sheet = [[UIActionSheet alloc]initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
        
    }
    [sheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSUInteger sourceType = 0;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
            case 0:
                return;
                break;
                case 1:
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
                case 2:
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            default:
                break;
        }
    }else{
        switch (buttonIndex) {
            case 0:
             
                break;
            case 1:
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                break;
        }
        
    }
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
    imagePickerController.delegate= self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.view.backgroundColor = [UIColor whiteColor];
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:^{
        
    }];
    
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    image= [info objectForKey:UIImagePickerControllerOriginalImage];
    [self saveImage:image withName:@"currentImage.png"];
    fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];    UIImage *saveImage = [[UIImage alloc]initWithContentsOfFile:fullPath];
    [self.imageView setImage:saveImage];
    [self.imageView setImage:image];
   
    
}
-(void)saveImage:(UIImage *)image withName:(NSString *)imageName{
    NSData *imageDate = UIImageJPEGRepresentation(image, 0.5);
    NSString *full = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    [imageDate writeToFile:fullPath atomically:NO];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
